package com.grieous.web.mvc.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.grieous.solr.SearchFile;

import domain.PageModel;

@Controller
public class HomeController {
	@RequestMapping("sf.htm")
	public String search(String search, Integer page, Integer pageSize,
			HttpServletRequest request) {
		if (search != null && search != "") {
			PageModel pageModel = SearchFile.search(search, page, pageSize);
			request.setAttribute("search", search);
			request.setAttribute("pageModel", pageModel);
		}
		return "search";
	}

	@RequestMapping("download.htm")
	public void downloadFile(String path, HttpServletResponse response,HttpServletRequest request)
			throws IOException {
		File file = new File(path);
		InputStream input = FileUtils.openInputStream(file);
		byte[] data = IOUtils.toByteArray(input);
		String fileName = URLEncoder.encode(file.getName(), "UTF-8");
		response.reset();
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Disposition", "attachment; filename=\""+ fileName + "\"");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");
		IOUtils.write(data, response.getOutputStream());
		IOUtils.closeQuietly(input);
	}
}
